<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules" v-bind="layout">
        <!-- 基本信息 -->
        <a-card title="基本信息" :bordered="false" style="margin-bottom: 16px">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="创建方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-radio-group v-model="model.planType" @change="onCreationTypeChange">
                  <a-radio :value="1">模板创建</a-radio>
                  <a-radio :value="2">自定义创建</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>

          <!-- 单订单选择 -->
          <a-row :gutter="24" v-if="model.planType != 3">
            <a-col :span="12">
              <a-form-model-item label="关联订单" prop="orderId">
                <j-select-production-order-modal
                  v-model="model.orderId"
                  :multiple="false"
                  placeholder="请选择生产订单"
                  :status="6"
                  @change="handleOrderChange"
                >
                </j-select-production-order-modal>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="计划名称" prop="planName">
                <a-input v-model="model.planName" placeholder="请输入计划名称"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>

          <!-- 订单明细选择 -->
          <a-row :gutter="24" v-if="model.orderId && orderDetails.length > 0">
            <a-col :span="24">
              <a-form-model-item label="选择产品明细" prop="selectedOrderDetails">
                <a-table
                  :columns="orderDetailColumns"
                  :dataSource="orderDetails"
                  :pagination="false"
                  size="small"
                  bordered
                  rowKey="id"
                  :row-selection="{
                    selectedRowKeys: selectedOrderDetailIds,
                    onChange: handleOrderDetailSelect,
                    onSelectAll: handleSelectAllOrderDetails,
                    type: 'checkbox',
                  }"
                >
                  <template slot="windowInfo" slot-scope="text, record">
                    <span>{{ record.windowNo }}</span>
                  </template>

                  <template slot="seriesInfo" slot-scope="text, record">
                    <span>{{ record.windowSeries }}</span>
                  </template>

                  <template slot="colorInfo" slot-scope="text, record">
                    <span>{{ record.windowColor }}</span>
                  </template>

                  <template slot="quantity" slot-scope="text">
                    <a-tag color="blue">{{ text }}件</a-tag>
                  </template>

                  <template slot="totalArea" slot-scope="text">
                    <span>{{ text }}㎡</span>
                  </template>
                </a-table>
              </a-form-model-item>
            </a-col>
          </a-row>

          <!-- 模板选择 -->
          <a-row :gutter="24" v-if="model.planType == 1">
            <a-col :span="12">
              <a-form-model-item label="生产模板" prop="templateId">
                <a-select
                  v-model="model.templateId"
                  placeholder="请选择生产模板"
                  @change="handleTemplateChange"
                  :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                >
                  <a-select-option v-for="template in templateOptions" :key="template.id" :value="template.id">
                    {{ template.templateName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>

            <a-col :span="12">
              <a-form-model-item label="优先级" prop="priority">
                <a-select v-model="model.priority" placeholder="请选择优先级">
                  <a-select-option :value="1">低</a-select-option>
                  <a-select-option :value="2">中</a-select-option>
                  <a-select-option :value="3">高</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="计划数量" prop="planQuantity">
                <a-input-number
                  v-model="model.planQuantity"
                  :min="1"
                  placeholder="根据订单明细自动计算"
                  :disabled="selectedOrderDetailIds.length > 0"
                  style="width: 100%"
                >
                </a-input-number>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="计划负责人" prop="planManager">
                <j-select-employee-modal
                  v-model="model.planManager"
                  :multiple="false"
                  placeholder="请选择计划负责人"
                  @change="handleManagerChange"
                >
                </j-select-employee-modal>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-model-item label="计划开始日期" prop="planStartDate">
                <a-date-picker v-model="model.planStartDate" placeholder="请选择开始日期" style="width: 100%">
                </a-date-picker>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="计划结束日期" prop="planEndDate">
                <a-date-picker v-model="model.planEndDate" placeholder="请选择结束日期" style="width: 100%">
                </a-date-picker>
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item label="备注" prop="remark">
                <a-textarea v-model="model.remark" placeholder="请输入备注" :rows="3"></a-textarea>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-card>

        <!-- 工种配置 -->
        <a-card
          title="工种配置"
          :bordered="false"
          v-if="model.planType == 2 || (model.planType == 1 && model.templateId)"
        >
          <template slot="extra">
            <a-button type="primary" size="small" @click="handleAddWorkType">
              <a-icon type="plus" />
              添加工种
            </a-button>
          </template>

          <!-- 工种配置表格 -->
          <a-table
            :columns="workTypeColumns"
            :dataSource="model.workTypes"
            :pagination="false"
            size="small"
            bordered
            rowKey="id"
            :scroll="{ x: 'max-content' }"
          >
            <template slot="workTypeName" slot-scope="text, record, index">
              <a-select
                v-model="record.workTypeId"
                placeholder="请选择工种"
                style="width: 100%"
                @change="(value) => handleWorkTypeChange(value, index)"
              >
                <a-select-option v-for="workType in workTypeOptions" :key="workType.id" :value="workType.id">
                  {{ workType.workTypeName }}
                </a-select-option>
              </a-select>
            </template>

            <template slot="sequence" slot-scope="text, record">
              <a-input-number v-model="record.sequence" :min="1" style="width: 100%"></a-input-number>
            </template>

            <template slot="taskQuantity" slot-scope="text, record">
              <a-input-number v-model="record.taskQuantity" :min="1" style="width: 100%"></a-input-number>
            </template>

            <template slot="planStartDate" slot-scope="text, record">
              <a-date-picker v-model="record.planStartDate" style="width: 100%"></a-date-picker>
            </template>

            <template slot="planEndDate" slot-scope="text, record">
              <a-date-picker v-model="record.planEndDate" style="width: 100%"></a-date-picker>
            </template>

            <template slot="pieceRateStandard" slot-scope="text, record, index">
              <a-select
                v-model="record.pieceRateStandardId"
                placeholder="请选择计件标准"
                style="width: 100%"
                @change="handlePieceRateStandardChange(record, index)"
                allowClear
                :getPopupContainer="(triggerNode) => triggerNode.parentNode"
              >
                <a-select-option
                  v-for="standard in getPieceRateStandardsByWorkType(record.workTypeId)"
                  :key="standard.id"
                  :value="standard.id"
                >
                  {{ standard.productCategory }} - {{ standard.productSpec }} ({{ standard.baseRate }}元/件)
                </a-select-option>
              </a-select>
            </template>

            <template slot="collaborationType" slot-scope="text, record">
              <a-select
                v-model="record.collaborationType"
                placeholder="协作类型"
                style="width: 100%"
                :getPopupContainer="(triggerNode) => triggerNode.parentNode"
              >
                <a-select-option :value="0">独立完成</a-select-option>
                <a-select-option :value="1">协作完成</a-select-option>
                <a-select-option :value="2">分段完成</a-select-option>
              </a-select>
            </template>

            <template slot="maxParticipants" slot-scope="text, record">
              <a-input-number
                v-model="record.maxParticipants"
                :min="1"
                :max="10"
                :disabled="record.collaborationType == 0"
                style="width: 100%"
              ></a-input-number>
            </template>

            <template slot="allowPartialClaim" slot-scope="text, record">
              <a-switch
                v-model="record.allowPartialClaim"
                :disabled="record.collaborationType == 0"
                checked-children="是"
                un-checked-children="否"
              />
            </template>

            <template slot="remark" slot-scope="text, record">
              <a-input v-model="record.remark" placeholder="备注"></a-input>
            </template>

            <template slot="action" slot-scope="text, record, index">
              <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteWorkType(index)">
                <a style="color: red">删除</a>
              </a-popconfirm>
            </template>
          </a-table>
        </a-card>
      </a-form-model>
    </a-spin>
    <!-- 计件标准选择模态框 -->
    <piece-rate-standard-select-modal ref="pieceRateStandardSelectModal" @ok="handlePieceRateStandardSelect" />
  </j-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import JSelectProductionOrderModal from '@/components/jeecgbiz/JSelectProductionOrderModal'
import JSelectEmployeeModal from '@/components/jeecgbiz/JSelectEmployeeModal'
import PieceRateStandardSelectModal from './PieceRateStandardSelectModal'
import moment from 'moment'

export default {
  name: 'PlanModal',
  components: {
    JSelectProductionOrderModal,
    JSelectEmployeeModal,
    PieceRateStandardSelectModal,
  },
  data() {
    return {
      title: '操作',
      width: 1200,
      visible: false,
      model: {
        planType: 1, // 计划类型(1-模板生成,2-自定义创建,3-合并计划)
        workTypes: [],
        orderId: '', // 关联订单ID
        orderNo: '', // 关联订单编号
        planName: '', // 计划名称
        templateId: '', // 生产模板ID
        templateName: '', // 生产模板名称
        planStartDate: null, // 计划开始日期
        planEndDate: null, // 计划结束日期
        planQuantity: null, // 计划数量
        planManager: '', // 计划负责人
        priority: 2, // 优先级(1-低,2-中,3-高)
        remark: '', // 备注
        orderDetailId: '', // 关联订单明细ID(多个用逗号分隔)
        productInfo: '', // 产品信息(门窗系列-窗号-颜色)
        selectedOrderDetails: [], // 合并计划选择的订单明细列表
      },
      orderDetails: [],
      selectedOrderDetailIds: [],
      estimatedWageCost: 0,
      // 合并计划相关数据
      selectedMergedOrderDetails: [],
      multiOrderSelectVisible: false,
      multiOrderSelectLoading: false,
      availableOrderDetails: [],
      tempSelectedOrderDetailIds: [],
      multiOrderSearchParams: {
        orderNo: '',
        customerName: '',
      },
      multiOrderPagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      // 按产品明细配置工种相关数据
      activeProductPanels: [],
      productWorkTypes: {}, // 存储每个产品明细对应的工种配置 {orderDetailId: [workTypes]}
      confirmLoading: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
      validatorRules: {
        planName: [{ required: true, message: '请输入计划名称!' }],
        planQuantity: [{ required: true, message: '请输入计划数量!' }],
        planStartDate: [{ required: true, message: '请选择计划开始日期!' }],
        orderId: [{ required: true, message: '请选择关联订单!', trigger: 'change' }],
        planEndDate: [{ required: true, message: '请选择计划结束日期!' }],
        templateId: [{ required: true, message: '请选择生产模板!', trigger: 'change' }],
      },
      url: {
        add: '/mes/plan/add',
        edit: '/mes/plan/edit',
        createFromTemplate: '/mes/plan/create-from-template',
        createCustom: '/mes/plan/create-custom',
        createMergedPlan: '/mes/plan/createMergedPlan',
        getTemplates: '/mes/template/list',
        getTemplateWorkTypes: '/mes/template/getWorkTypes',
        getPieceRateStandardsByWorkType: '/mes/pieceRateStandard/getByWorkType',
        getWorkTypes: '/mes/worktype/list',
        getOrderDetails: '/oms/productSalesOrder/getOrderDetails',
        getAvailableOrderDetails: '/oms/productSalesOrderDetail/getAvailableForProduction',
        getPieceRateStandards: '/mes/pieceRateStandard/getValidStandards',
        calculateWageCost: '/mes/employeePieceWage/calculateCost',
      },
      orderDetailColumns: [
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 120,
          scopedSlots: { customRender: 'windowInfo' },
        },
        {
          title: '系列',
          dataIndex: 'windowSeries',
          width: 120,
          scopedSlots: { customRender: 'seriesInfo' },
        },
        {
          title: '颜色',
          dataIndex: 'windowColor',
          width: 120,
          scopedSlots: { customRender: 'colorInfo' },
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 100,
          scopedSlots: { customRender: 'quantity' },
        },
        {
          title: '总面积',
          dataIndex: 'totalArea',
          width: 120,
          scopedSlots: { customRender: 'totalArea' },
        },
      ],
      templateOptions: [],
      workTypeOptions: [], // 工种选项
      pieceRateStandards: [], // 计件标准列表
      workTypeColumns: [
        {
          title: '工种',
          dataIndex: 'workTypeName',
          width: 150,
          scopedSlots: { customRender: 'workTypeName' },
        },
        {
          title: '工序顺序',
          dataIndex: 'sequence',
          width: 100,
          scopedSlots: { customRender: 'sequence' },
        },
        {
          title: '任务数量',
          dataIndex: 'taskQuantity',
          width: 100,
          scopedSlots: { customRender: 'taskQuantity' },
        },
        {
          title: '计划开始日期',
          dataIndex: 'planStartDate',
          width: 150,
          scopedSlots: { customRender: 'planStartDate' },
        },
        {
          title: '计划结束日期',
          dataIndex: 'planEndDate',
          width: 150,
          scopedSlots: { customRender: 'planEndDate' },
        },
        {
          title: '计件标准',
          dataIndex: 'pieceRateStandardId',
          width: 150,
          scopedSlots: { customRender: 'pieceRateStandard' },
        },
        {
          title: '协作类型',
          dataIndex: 'collaborationType',
          width: 120,
          scopedSlots: { customRender: 'collaborationType' },
        },
        {
          title: '最大参与人数',
          dataIndex: 'maxParticipants',
          width: 120,
          scopedSlots: { customRender: 'maxParticipants' },
        },
        {
          title: '允许部分领取',
          dataIndex: 'allowPartialClaim',
          width: 120,
          scopedSlots: { customRender: 'allowPartialClaim' },
        },
        {
          title: '备注',
          dataIndex: 'remark',
          scopedSlots: { customRender: 'remark' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
    }
  },
  created() {
    this.loadTemplates()
    this.loadWorkTypes()
  },
  methods: {
    add() {
      this.edit({})
    },
    edit(record) {
      this.title = record.id ? '编辑' : '新增'
      this.visible = true

      // 合并默认值和传入的记录数据
      this.model = Object.assign(
        {
          planType: 1,
          workTypes: [],
          orderId: '',
          orderNo: '',
          planName: '',
          templateId: '',
          templateName: '',
          planStartDate: record.id ? null : moment(),
          planEndDate: null,
          planQuantity: null,
          planManager: '',
          priority: 2,
          remark: '',
        },
        record
      )
      this.model.planType = record.id ? record.planType || 1 : 1
      if (!this.model.workTypes) {
        this.model.workTypes = []
      }
      // 如果是编辑模式且有订单明细ID，转换为数组
      if (record.id && record.orderDetailId) {
        this.selectedOrderDetailIds = record.orderDetailId.split(',').filter((id) => id)
      } else {
        this.selectedOrderDetailIds = []
      }

      // 合并计划相关数据初始化
      if (record.selectedOrderDetails) {
        this.selectedMergedOrderDetails = record.selectedOrderDetails
      } else {
        this.selectedMergedOrderDetails = []
      }

      // 如果是编辑模式，加载订单明细
      if (record.id && this.selectedOrderDetailIds.length > 0) {
        this.loadOrderDetails()
      }

      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''

          if (this.model.planType === 1) {
            // 基于模板创建
            httpurl = this.url.createFromTemplate
            method = 'post'
          } else if (this.model.planType === 2) {
            // 自定义创建
            httpurl = this.url.createCustom
            method = 'post'
          } else if (this.model.planType === 3) {
            // 合并计划创建
            httpurl = this.url.createMergedPlan
            method = 'post'
          }

          let formData = this.getFormData()
          httpAction(httpurl, formData, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.close()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    getFormData() {
      let formData = Object.assign({}, this.model)

      // 处理日期格式
      if (formData.planStartDate) {
        formData.planStartDate = formData.planStartDate.format('YYYY-MM-DD')
      }
      if (formData.planEndDate) {
        formData.planEndDate = formData.planEndDate.format('YYYY-MM-DD')
      }

      // 处理订单明细ID - 将数组转换为逗号分隔的字符串
      if (this.selectedOrderDetailIds && this.selectedOrderDetailIds.length > 0) {
        formData.orderDetailId = this.selectedOrderDetailIds.join(',')
        formData.orderDetailIds = this.selectedOrderDetailIds
      }

      // 处理合并计划的订单明细
      if (this.model.planType === 3 && this.selectedMergedOrderDetails && this.selectedMergedOrderDetails.length > 0) {
        formData.orderDetailIds = this.selectedMergedOrderDetails.map((item) => item.id)
        formData.selectedOrderDetails = this.selectedMergedOrderDetails
      }

      // 处理产品信息 - 根据选中的订单明细生成产品信息
      if (this.selectedOrderDetailIds && this.selectedOrderDetailIds.length > 0) {
        const selectedDetails = this.orderDetails.filter((item) => this.selectedOrderDetailIds.includes(item.id))
        formData.productInfo = selectedDetails
          .map((item) => `${item.windowSeries}-${item.windowNo}-${item.windowColor}`)
          .join(';')
      } else if (
        this.model.planType === 3 &&
        this.selectedMergedOrderDetails &&
        this.selectedMergedOrderDetails.length > 0
      ) {
        formData.productInfo = this.selectedMergedOrderDetails
          .map((item) => `${item.seriesName}-${item.windowNo}-${item.colorName}`)
          .join(';')
      }

      // 处理工种任务日期
      if (formData.workTypes && formData.workTypes.length > 0) {
        formData.tasks = formData.workTypes.map((item) => {
          let task = Object.assign({}, item)
          if (task.planStartDate) {
            task.planStartDate = task.planStartDate.format('YYYY-MM-DD')
          }
          if (task.planEndDate) {
            task.planEndDate = task.planEndDate.format('YYYY-MM-DD')
          }
          return task
        })
        delete formData.workTypes
      }

      return formData
    },
    onCreationTypeChange(e) {
      this.model.planType = e.target.value
      if (this.model.planType === 1) {
        // 切换到模板创建时清空自定义工种
        this.model.workTypes = []
        // 添加模板ID验证规则
        this.validatorRules.templateId = [{ required: true, message: '请选择生产模板!', trigger: 'change' }]
      } else if (this.model.planType === 2) {
        // 切换到自定义创建时清空模板ID
        this.model.templateId = undefined
        // 移除模板ID验证规则
        delete this.validatorRules.templateId
      } else if (this.model.planType === 3) {
        // 切换到合并计划时清空模板ID和工种
        this.model.templateId = undefined
        this.model.workTypes = []
        delete this.validatorRules.templateId
      }
      // 强制更新视图
      this.$forceUpdate()
    },
    // 多订单选择相关方法
    showMultiOrderSelect() {
      this.multiOrderSelectVisible = true
      this.tempSelectedOrderDetailIds = [...this.selectedMergedOrderDetails.map((item) => item.id)]
      this.loadAvailableOrderDetails()
    },
    handleMultiOrderSelectOk() {
      const selectedDetails = this.availableOrderDetails.filter((item) =>
        this.tempSelectedOrderDetailIds.includes(item.id)
      )
      this.selectedMergedOrderDetails = selectedDetails

      // 自动生成计划名称
      if (selectedDetails.length > 0) {
        const customerNames = [...new Set(selectedDetails.map((item) => item.customerName))]
        const seriesNames = [...new Set(selectedDetails.map((item) => item.seriesName))]
        this.model.planName = `${customerNames.join('+')}合并计划-${seriesNames.join('+')}`

        // 计算总数量
        this.model.planQuantity = selectedDetails.reduce((sum, item) => sum + item.quantity, 0)
      }

      this.multiOrderSelectVisible = false
    },
    handleMultiOrderSelectCancel() {
      this.multiOrderSelectVisible = false
      this.tempSelectedOrderDetailIds = []
    },
    loadAvailableOrderDetails() {
      this.multiOrderSelectLoading = true
      const params = {
        pageNo: this.multiOrderPagination.current,
        pageSize: this.multiOrderPagination.pageSize,
        ...this.multiOrderSearchParams,
      }

      getAction(this.url.getAvailableOrderDetails, params)
        .then((res) => {
          if (res.success) {
            this.availableOrderDetails = res.result.records || []
            this.multiOrderPagination.total = res.result.total || 0
          }
        })
        .finally(() => {
          this.multiOrderSelectLoading = false
        })
    },
    handleMultiOrderSearch() {
      this.multiOrderPagination.current = 1
      this.loadAvailableOrderDetails()
    },
    handleMultiOrderTableChange(pagination) {
      this.multiOrderPagination = pagination
      this.loadAvailableOrderDetails()
    },
    onMultiOrderSelectionChange(selectedRowKeys) {
      this.tempSelectedOrderDetailIds = selectedRowKeys
    },
    removeSelectedOrderDetail(index) {
      this.selectedMergedOrderDetails.splice(index, 1)
      // 重新计算总数量
      this.model.planQuantity = this.selectedMergedOrderDetails.reduce((sum, item) => sum + item.quantity, 0)
    },
    handleCreateTypeChange(e) {
      this.onCreationTypeChange(e)
    },
    loadTemplates() {
      getAction(this.url.getTemplates, { pageSize: 999, status: 1 }).then((res) => {
        if (res.success) {
          this.templateOptions = res.result.records || []
        }
      })
    },
    loadWorkTypes() {
      getAction(this.url.getWorkTypes, { pageSize: 999, status: 1 }).then((res) => {
        if (res.success) {
          this.workTypeOptions = res.result.records || []
        }
      })
    },
    handleAddWorkType() {
      // 获取当前计划数量，如果为空或0则默认为1
      const defaultQuantity = this.model.planQuantity && this.model.planQuantity > 0 ? this.model.planQuantity : 1

      // 保持日期的原始格式，ADatePicker会自动处理
      const startDate = this.model.planStartDate
      const endDate = this.model.planEndDate
      const newWorkType = {
        workTypeId: '',
        workTypeCode: '',
        workTypeName: '',
        sequence: this.model.workTypes.length + 1,
        taskQuantity: defaultQuantity,
        planStartDate: startDate,
        planEndDate: endDate,
        isRequired: 1,
        pieceRateStandardId: '',
        collaborationType: 0,
        maxParticipants: 1,
        allowPartialClaim: true,
        remark: '',
      }
      // 使用$set确保响应式更新
      const newWorkTypes = [...this.model.workTypes, newWorkType]
      this.$set(this.model, 'workTypes', newWorkTypes)

      // 强制更新视图
      this.$forceUpdate()
    },
    handleDeleteWorkType(index) {
      this.model.workTypes.splice(index, 1)
      // 重新排序
      this.model.workTypes.forEach((item, idx) => {
        item.sequence = idx + 1
      })
    },
    handleWorkTypeChange(value, index) {
      const selectedWorkType = this.workTypeOptions.find((item) => item.id == value)
      if (selectedWorkType) {
        // 创建新的工种对象，确保Vue能检测到变化
        const updatedWorkType = {
          ...this.model.workTypes[index],
          workTypeId: value,
          workTypeCode: selectedWorkType.workTypeCode,
          workTypeName: selectedWorkType.workTypeName,
        }
        // 替换整个数组以确保响应式更新
        const newWorkTypes = [...this.model.workTypes]
        newWorkTypes[index] = updatedWorkType
        this.$set(this.model, 'workTypes', newWorkTypes)

        // 使用nextTick确保DOM更新完成
        this.$nextTick(() => {
          this.$forceUpdate()
        })

        // 当工种变更时，加载对应的计件标准
        this.loadPieceRateStandardsByWorkType(value)
      }
    },

    // 加载指定工种的计件标准
    loadPieceRateStandardsByWorkType(workTypeId) {
      if (!workTypeId) return
      getAction(this.url.getPieceRateStandardsByWorkType, { workTypeId })
        .then((res) => {
          console.log('加载工种计件标准', res)
          if (res.success && res.result) {
            // 更新计件标准列表，按工种ID分组
            this.pieceRateStandards = this.pieceRateStandards.filter((item) => item.workTypeId !== workTypeId)
            this.pieceRateStandards.push(...res.result)

            // 查找默认计件标准并设置到对应的工种中
            const defaultStandard = res.result.find((item) => item.isDefault == 1)
            if (defaultStandard) {
              // 找到使用该工种的所有记录并设置默认计件标准
              const updatedWorkTypes = [...this.model.workTypes]
              let hasUpdate = false
              updatedWorkTypes.forEach((workType, index) => {
                if (workType.workTypeId === workTypeId && !workType.pieceRateStandardId) {
                  workType.pieceRateStandardId = defaultStandard.id
                  hasUpdate = true
                }
              })
              if (hasUpdate) {
                this.$set(this.model, 'workTypes', updatedWorkTypes)
              }
            }
          }
        })
        .catch(() => {
          this.$message.warning('加载计件标准失败')
        })
    },

    // 根据工种ID获取计件标准列表
    getPieceRateStandardsByWorkType(workTypeId) {
      return this.pieceRateStandards.filter((item) => item.workTypeId === workTypeId)
    },

    // 处理计件标准变更
    handlePieceRateStandardChange(record, index) {
      // 可以在这里添加计件标准变更后的逻辑
      console.log('计件标准变更:', record.pieceRateStandardId)
    },
    handleOrderChange(orderId) {
      this.model.orderId = orderId
      if (orderId) {
        // 先获取订单信息，然后生成计划名称
        this.getOrderInfoAndGenerateName(orderId)
        this.loadOrderDetails(orderId)
      } else {
        this.orderDetails = []
        this.selectedOrderDetailIds = []
        this.model.planQuantity = null
        this.model.planName = ''
        this.model.orderNo = ''
      }
    },

    // 获取订单信息并生成计划名称
    getOrderInfoAndGenerateName(orderId) {
      // 通过API获取订单信息
      getAction('/oms/productSalesOrder/queryById', { id: orderId })
        .then((res) => {
          if (res.success && res.result) {
            this.model.orderNo = res.result.orderNo
            // 生成计划名称 订单编号+当前时间，时间格式为YYYYMMDDHHmm
            if (res.result.orderNo) {
              const currentDateTime = new Date()
              const year = currentDateTime.getFullYear()
              const month = String(currentDateTime.getMonth() + 1).padStart(2, '0')
              const day = String(currentDateTime.getDate()).padStart(2, '0')
              const hours = String(currentDateTime.getHours()).padStart(2, '0')
              const minutes = String(currentDateTime.getMinutes()).padStart(2, '0')
              const dateStr = `${year}${month}${day}`
              const timestamp = `${hours}${minutes}`
              this.model.planName = `${res.result.orderNo}_${dateStr}_${timestamp}`
            }
          }
        })
        .catch((error) => {
          console.error('获取订单信息失败:', error)
        })
    },
    handleOrderDetailSelect(selectedRowKeys) {
      this.selectedOrderDetailIds = selectedRowKeys
      this.calculatePlanQuantity()
      this.calculateEstimatedWageCost()
    },
    handleTemplateChange(templateId) {
      // 根据模板自动填充信息
      const selectedTemplate = this.templateOptions.find((t) => t.id === templateId)
      if (selectedTemplate) {
        this.model.templateId = templateId
        this.model.templateName = selectedTemplate.templateName
      }
      this.loadTemplateWorkTypes(templateId)
    },
    handleSelectAllOrderDetails(selected, selectedRows, changeRows) {
      if (selected) {
        // 全选：选择所有订单明细
        this.selectedOrderDetailIds = this.orderDetails.map((item) => item.id)
      } else {
        // 取消全选：清空选择
        this.selectedOrderDetailIds = []
      }
      // 重新计算计划数量和预估成本
      this.calculatePlanQuantity()
      this.calculateEstimatedWageCost()
    },
    calculatePlanQuantity() {
      if (this.selectedOrderDetailIds.length > 0) {
        const totalQuantity = this.orderDetails
          .filter((item) => this.selectedOrderDetailIds.includes(item.id))
          .reduce((sum, item) => sum + (item.quantity || 0), 0)
        this.model.planQuantity = totalQuantity
      } else {
        this.model.planQuantity = null
      }
    },
    handleManagerChange(managerId) {
      this.model.planManager = managerId
    },
    loadOrderDetails(orderId) {
      getAction(this.url.getOrderDetails, { orderId })
        .then((res) => {
          if (res.success) {
            this.orderDetails = res.result || []
            // 自动选择所有订单明细
            this.selectedOrderDetailIds = this.orderDetails.map((item) => item.id)
            // 自动计算计划数量
            this.calculatePlanQuantity()
            // 计算预估工资成本
            this.calculateEstimatedWageCost()
          } else {
            this.$message.warning(res.message)
            this.orderDetails = []
            this.selectedOrderDetailIds = []
          }
        })
        .catch(() => {
          this.orderDetails = []
          this.selectedOrderDetailIds = []
        })
    },

    // 计算预估工资成本
    calculateEstimatedWageCost() {
      if (this.selectedOrderDetailIds.length === 0) {
        this.estimatedWageCost = 0
        return
      }

      const selectedDetails = this.orderDetails.filter((item) => this.selectedOrderDetailIds.includes(item.id))

      // 简单估算：每个产品明细 * 基础单价 * 工种数量
      let totalCost = 0
      selectedDetails.forEach((detail) => {
        const quantity = detail.quantity || 0
        const estimatedUnitCost = 50 // 假设平均每件50元工资成本
        const workTypeCount = this.workTypeOptions.length || 5 // 假设5个工种
        totalCost += quantity * estimatedUnitCost * workTypeCount
      })

      this.estimatedWageCost = totalCost
    },

    // 处理临时订单明细选择
    handleTempOrderDetailSelect(selectedRowKeys) {
      this.tempSelectedOrderDetailIds = selectedRowKeys
    },

    // 处理临时全选订单明细
    handleTempSelectAllOrderDetails(selected, selectedRows, changeRows) {
      if (selected) {
        // 全选当前页
        this.tempSelectedOrderDetailIds = this.availableOrderDetails.map((item) => item.id)
      } else {
        // 取消全选
        this.tempSelectedOrderDetailIds = []
      }
    },

    // 显示多订单选择弹窗
    showMultiOrderSelectModal() {
      this.multiOrderSelectVisible = true
      this.loadAvailableOrderDetails()
    },

    // 移除合并计划中的订单明细
    removeMergedOrderDetail(orderDetailId) {
      this.selectedMergedOrderDetails = this.selectedMergedOrderDetails.filter((item) => item.id !== orderDetailId)
    },

    // 加载模板工种配置
    loadTemplateWorkTypes(templateId) {
      console.log('加载模板工种配置', templateId)

      getAction(this.url.getTemplateWorkTypes, { templateId })
        .then((res) => {
          if (res.success && res.result && res.result.length > 0) {
            // 将模板工种配置加载到当前计划中
            this.model.workTypes = res.result.map((item, index) => ({
              workTypeId: item.workTypeId,
              workTypeCode: item.workTypeCode,
              workTypeName: item.workTypeName,
              sequence: item.sequence || index + 1,
              taskQuantity: this.model.planQuantity || item.taskQuantity || 1,
              planStartDate: this.model.planStartDate,
              planEndDate: this.model.planEndDate,
              isRequired: item.isRequired || 1,
              pieceRateStandardId: '',
              collaborationType: item.collaborationType || 0,
              maxParticipants: item.maxParticipants || 1,
              allowPartialClaim: item.allowPartialClaim !== undefined ? item.allowPartialClaim : true,
              remark: item.remark || '',
            }))

            // 为每个工种加载计件标准并设置默认值
            this.model.workTypes.forEach((workType, index) => {
              this.loadAndSetDefaultPieceRateStandard(workType.workTypeId, index)
            })

            // 强制更新视图
            this.$forceUpdate()
          } else {
            // 如果模板没有工种配置，清空工种列表
            this.model.workTypes = []
          }
        })
        .catch(() => {
          this.$message.warning('加载模板工种配置失败')
          this.model.workTypes = []
        })
    },

    // 加载工种的计件标准并设置默认值
    loadAndSetDefaultPieceRateStandard(workTypeId, workTypeIndex) {
      getAction(this.url.getPieceRateStandardsByWorkType, { workTypeId })
        .then((res) => {
          console.log('加载工种计件标准', res)
          if (res.success && res.result && res.result.length > 0) {
            // 更新计件标准列表
            this.pieceRateStandards = this.pieceRateStandards.filter((item) => item.workTypeId !== workTypeId)
            this.pieceRateStandards.push(...res.result)
            // 查找默认计件标准
            const defaultStandard = res.result.find((item) => item.isDefault === 1)
            if (defaultStandard && this.model.workTypes[workTypeIndex]) {
              // 设置默认计件标准
              const updatedWorkTypes = [...this.model.workTypes]
              updatedWorkTypes[workTypeIndex].pieceRateStandardId = defaultStandard.id
              this.$set(this.model, 'workTypes', updatedWorkTypes)
            }
          }
        })
        .catch(() => {
          console.warn(`加载工种 ${workTypeId} 的计件标准失败`)
        })
    },

    // 处理计件标准选择
    handlePieceRateStandardSelect(selectedStandard, workTypeIndex) {
      if (selectedStandard && this.model.workTypes[workTypeIndex]) {
        const updatedWorkTypes = [...this.model.workTypes]
        updatedWorkTypes[workTypeIndex].pieceRateStandardId = selectedStandard.id
        this.$set(this.model, 'workTypes', updatedWorkTypes)
      }
    },

    // 获取产品明细对应的工种配置
    getProductWorkTypes(orderDetailId) {
      return this.productWorkTypes[orderDetailId] || []
    },

    // 为产品明细添加工种
    handleAddProductWorkType(orderDetailId) {
      if (!this.productWorkTypes[orderDetailId]) {
        this.$set(this.productWorkTypes, orderDetailId, [])
      }

      const newWorkType = {
        id: Date.now().toString(),
        workTypeId: '',
        workTypeName: '',
        sequence: this.productWorkTypes[orderDetailId].length + 1,
        collaborationType: 0,
        maxParticipants: 1,
        allowPartialClaim: false,
      }

      this.productWorkTypes[orderDetailId].push(newWorkType)
    },

    // 删除产品明细的工种
    handleDeleteProductWorkType(orderDetailId, workTypeRecord) {
      const workTypes = this.productWorkTypes[orderDetailId] || []
      const index = workTypes.findIndex((item) => item.id === workTypeRecord.id)
      if (index > -1) {
        workTypes.splice(index, 1)
      }
    },

    // 处理产品明细工种变化
    handleProductWorkTypeChange(workTypeId, orderDetailId, record) {
      const selectedWorkType = this.workTypeOptions.find((item) => item.id === workTypeId)
      if (selectedWorkType) {
        record.workTypeName = selectedWorkType.workTypeName
        record.workTypeCode = selectedWorkType.workTypeCode
      }
    },

    // 批量配置工种
    handleBatchConfigWorkTypes() {
      this.$confirm({
        title: '批量配置工种',
        content: '是否为所有选中的产品明细批量添加相同的工种配置？',
        onOk: () => {
          // 获取第一个产品明细的工种配置作为模板
          const firstOrderDetail = this.selectedMergedOrderDetails[0]
          if (!firstOrderDetail) return

          const templateWorkTypes = this.productWorkTypes[firstOrderDetail.id] || []
          if (templateWorkTypes.length === 0) {
            this.$message.warning('请先为第一个产品明细配置工种')
            return
          }

          // 为其他产品明细复制工种配置
          this.selectedMergedOrderDetails.forEach((orderDetail, index) => {
            if (index === 0) return // 跳过第一个

            const copiedWorkTypes = templateWorkTypes.map((workType) => ({
              ...workType,
              id: `${orderDetail.id}_${workType.workTypeId}_${Date.now()}`,
            }))

            this.$set(this.productWorkTypes, orderDetail.id, copiedWorkTypes)
          })

          this.$message.success('批量配置工种成功')
        },
      })
    },
  },
}
</script>

<style lang="less" scoped>
</style>
